package com.example.tourmemory.data.getdata;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import com.example.tourmemory.data.record.RecordData;

public class RecordDataBank {
    private static final String PICTURE_FILE_PREFIX = "images";
    private static final String RECORD_FILE_DIRECTORY = "records";
    private static final String RECORD_FILE_DATA_FILE = "record.data";

    private static File GetRecordBankDir(Context context){
        File recordDir = new File(context.getFilesDir(), RECORD_FILE_DIRECTORY);
        // 创建文件夹
        boolean isCreated = false;
        if(!recordDir.exists())
            isCreated = recordDir.mkdir();
        if(isCreated)
            Log.d("File", "Created record directory");
        else {
            Log.d("File", "Load record directory");
        }
        return recordDir;
    }

    public static File GetRecordDir(Context context, RecordData recordData){
        return new File(GetRecordBankDir(context), recordData.getDateTime().toString());
    }

    public static void SaveRecords(Context context, ArrayList<RecordData> recordDataList){
        for(RecordData recordData : recordDataList)
            saveRecord(context, recordData);
    }

    public static void saveRecord(Context context, RecordData recordData){
        // 创建储存该记录的文件夹
        File recordDirectory = GetRecordDir(context, recordData);
        recordDirectory.mkdir();

        // 将图片储存到该目录下
        ArrayList<String> savePath = new ArrayList<>();
        for(int i = 0; i < recordData.getPicCount(); ++i){
            // 储存文件名称
            String imageFileName = PICTURE_FILE_PREFIX + i + ".png";
            // 将储存位置保存，下次读取的时候复用
            savePath.add(imageFileName);
            // 储存图片到指定路径
            openDirSaveBitmap(recordData.getBitmap(i), recordDirectory, imageFileName);
        }
        recordData.setPicturePathList(savePath);

        // 储存非资源变量到该目录下
        try{
            FileOutputStream recordOut = new FileOutputStream(new File(recordDirectory, RECORD_FILE_DATA_FILE));
            ObjectOutputStream objectOut = new ObjectOutputStream(recordOut);
            objectOut.writeObject(recordData);
            objectOut.close();
            recordOut.close();
            Log.d("Serialization", "SaveRecord: " + recordData.getDateTime().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ArrayList<RecordData> LoadRecords(Context context){
        ArrayList<RecordData> recordDataBank = new ArrayList<>();
        File recordDir = GetRecordBankDir(context);
        // 读取文件夹
        File[] recordFiles = recordDir.listFiles();
        if(recordFiles != null) {
            for (File recordDirectory : recordFiles) {
                RecordData recordData = loadRecord(recordDirectory);
                if(recordData != null)
                    recordDataBank.add(recordData);
            }
        }
        if(recordDataBank.isEmpty())
            // 读空时生成默认记录
            recordDataBank.add(new RecordData(context));
        return recordDataBank;
    }

    public static RecordData loadRecord(File recordDirectory){
        RecordData recordData = null;
        // 读取非资源变量
        try {
            FileInputStream recordIn = new FileInputStream(new File(recordDirectory, RECORD_FILE_DATA_FILE));
            ObjectInputStream objectIn = new ObjectInputStream(recordIn);
            recordData = (RecordData) objectIn.readObject();
            objectIn.close();
            recordIn.close();
            Log.d("Serialization", "LoadRecord: " + recordData.getDateTime().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(recordData == null)
            return null;
        // 从文件夹读取图片
        ArrayList<Bitmap> bitmaps = new ArrayList<>();
        for(int j = 0; j < recordData.getPicCount(); ++j){
            // 打开文件读取照片
            String fileName = recordData.getPicturePath(j);
            bitmaps.add(openDirReadBitmap(recordDirectory, fileName));
        }
        recordData.setBitmaps(bitmaps);
        return recordData;
    }

    public static void deleteRecord(Context context, RecordData recordData){
        File recordDirectory = GetRecordDir(context, recordData);
        deleteDirectory(recordDirectory);
    }

    public static void openDirSaveBitmap(Bitmap bitmap, File fileDir, String fileName) {
        // 将图片保存到指定文件夹
        File imageFile = new File(fileDir, fileName);
        try{
            FileOutputStream imageOut = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageOut);
            imageOut.close();
            Log.d("Saved Image", imageFile.getPath());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Bitmap openDirReadBitmap(File fileDir, String fileName){
        // 从文件夹读取图片
        Bitmap bitmap = null;
        File imageFile = new File(fileDir, fileName);
        try{
            FileInputStream imageIn = new FileInputStream(imageFile);
            bitmap = BitmapFactory.decodeStream(imageIn);
            imageIn.close();
            Log.d("Read Image", imageFile.getPath());
        }catch (Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }

    public static boolean deleteDirectory(File directory) {
        boolean result = true;
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        result &= deleteDirectory(file);
                    } else {
                        result &= file.delete();
                    }
                }
            }
            result &= directory.delete();
        }
        return result;
    }


    public static File saveBitmapToTempFile(Context context, Bitmap bitmap){
        // 将图片保存到临时空间
        File cacheDir = context.getCacheDir();
        File imageFile = new File(cacheDir, "temp" + System.currentTimeMillis() + ".png");

        try{
            // 创建临时文件
            FileOutputStream imageOut = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageOut);
            imageOut.close();
            Log.d("Saved Temp Image", imageFile.getPath());
        }catch (Exception e){
            e.printStackTrace();
        }
        return imageFile;
    }

    public static Uri getFileUri(Context context, File imageFile) {
        Uri uri;

        // 如果你的应用目标是Android N及以上，使用FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context,
                    context.getApplicationContext().getPackageName() + ".fileprovider",
                    imageFile);
        } else {
            uri = Uri.fromFile(imageFile);
        }
        return uri;
    }
}
